from django import forms
from django_redis import get_redis_connection

from authApp.models import UserInfo
from authApp.utils import encrypt


class RegisterForm(forms.Form):
    username = forms.CharField(label="用户名", max_length=20, min_length=5, error_messages={
        'required': '请输入用户名！',
        'max_length': '用户名长度在5~20个字段之间！',
        'min_length': '用户名长度在5~20个字段之间！'
    }, widget=forms.TextInput())
    email = forms.EmailField(label="邮箱", error_messages={
        'required': '请输入邮箱！',
        'invalid': '请传入一个正确的邮箱！'
    }, widget=forms.EmailInput())
    captcha = forms.CharField(label="验证码", max_length=6, min_length=6, error_messages={
        'required': '请输入验证码！',
        'max_length': '验证码错误！',
        'min_length': '验证码错误！'
    }, widget=forms.TextInput())
    password = forms.CharField(label="密码", max_length=20, min_length=6, error_messages={
        'required': '请输入密码！',
        'max_length': '密码长度长度在6~20个字段之间！',
        'min_length': '密码长度长度在6~20个字段之间！'
    }, widget=forms.PasswordInput())
    confirm_password = forms.CharField(label="重复密码", max_length=20, min_length=6, error_messages={
        'required': '请输入密码！',
        'max_length': '密码长度长度在6~20个字段之间！',
        'min_length': '密码长度长度在6~20个字段之间！'
    }, widget=forms.PasswordInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)
            field.widget.attrs['id'] = name

    def clean_email(self):
        email = self.cleaned_data['email']
        exists = UserInfo.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('账号邮箱已存在！')
        return email

    def clean_password(self):
        password = self.cleaned_data['password']
        return encrypt.md5(password)

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = encrypt.md5(self.cleaned_data['confirm_password'])
        if password != confirm_password:
            raise forms.ValidationError('两次输入的密码不一致')
        return confirm_password

    def clean_captcha(self):
        captcha = self.cleaned_data['captcha']
        email = self.cleaned_data['email']
        conn = get_redis_connection()
        redis_code = conn.get(email)
        if not redis_code:
            raise forms.ValidationError('验证码失效或未发送，请重新发送')
        redis_code_str = redis_code.decode('utf-8')
        if captcha.strip() != redis_code_str:
            raise forms.ValidationError('验证码错误,请重新输入')


class LoginForm(forms.Form):
    email = forms.EmailField(error_messages={
        'required': '请输入邮箱！',
        'invalid': '请传入一个正确的邮箱！'
    })
    captcha = forms.CharField(max_length=4, min_length=4, error_messages={
    })
    password = forms.CharField(max_length=20, min_length=6, error_messages={
        'required': '请输入密码！',
        'max_length': '密码长度长度在6~20个字段之间！',
        'min_length': '密码长度长度在6~20个字段之间！'
    })
    remember = forms.IntegerField(required=False)
    hashkey = forms.CharField(required=True, widget=forms.HiddenInput())

    def clean_password(self):
        password = self.cleaned_data['password']
        return encrypt.md5(password)
